/**
 * @param {string} str 
 * @returns 
 */
function findDuplicateSubstrings(str) {
    const len = str.length;
    const result = new Set();

    for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            const substring = str.slice(i, j + 1);

            if (str.indexOf(substring, j + 1) !== -1) {
                result.add(substring);
            }
        }
    }

    return Array.from(result);
}


/**
 * @param {string} str 
 * @returns 
 */
function findLongestDuplicateSubstring(str) {
    const len = str.length;
    let longestSubstring = "";

    for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            const substring = str.slice(i, j + 1);

            if (str.indexOf(substring, j + 1) !== -1 && substring.length > longestSubstring.length) {
                longestSubstring = substring;
            }
        }
    }

    return longestSubstring;
}

/**
 * 
 * @param {string} str 
 */
function findSame(str) {
    let res = [];
    while (true) {
        var sub = findLongestDuplicateSubstring(str)
        if (sub) {
            console.log(sub)
            res.push(sub)
            str = str.replace(new RegExp(sub, 'g'), "")
        } else {
            break
        }
    }
    return res;
}

function show() {
    const text = document.getElementById("text").value
    const tg = document.getElementById("res")
    findSame(text).forEach(v => {
        var d = document.createElement("div")
        d.innerText = v;
        tg.appendChild(d)
    })
}
document.getElementById("findSame").addEventListener("click", show)

// test11();

function test11() {
    const inputString1 = "ababcababc";
    const duplicates = findDuplicateSubstrings(inputString1);

    console.log("重复的子字符串:", duplicates);

    const inputString = "ababcababc";
    const longestDuplicate = findLongestDuplicateSubstring(inputString);

    console.log("最长相同子串:", longestDuplicate);
}
